<template>
  <div>
    <h1>品牌管理</h1>
    <el-button
      type="primary"
      icon="plus"
      @click="showDialog"
      style="margin-bottom: 10px"
      >新增品牌</el-button
    >

    <el-table style="width: 100%" :data="list" border>
      <el-table-column
        type="index"
        label="序号"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        align="center"
      ></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" align="center">
        <template #default="scope">
          <img :src="scope.row.logoUrl" style="width: 150px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="warning" icon="edit" @click="updateTradeMark(row)"
            >编辑</el-button
          >
          <el-button type="danger" icon="delete" @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 20px; text-align: center"
      :current-page="page"
      :total="total"
      :page-size="limit"
      :pager-count="7"
      :page-sizes="[3, 5, 10]"
      background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      @current-change="getPageList"
      @size-change="handleSizeChange"
    />

    <!-- 新增或修改品牌对话框结构 -->
    <el-dialog v-model="dialogFormVisible" >
      <span class="title">
        品牌信息
      </span>
      <el-form :model="tmForm" :rules="rules" ref="ruleForm" style="width: 80%;padding: 10px;">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tmForm.tmName" autocomplete="off" placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            list-type="picture-card"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <el-icon v-else ><Plus /></el-icon>
            <template v-slot:tip>
    <div class="el-upload__tip">注意:只能上传jpg/png文件,且不超过5M!</div>
  </template>
          </el-upload>
        </el-form-item>
        <el-form-item >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button >
        </el-form-item>
    </el-form>
    </el-dialog>
  </div>
</template>
  
  <script>
export default {
  name: "TradeMark",
  data() {
    // 自定义校验规则
    var validateTmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌名称2-10位"));
      } else {
        callback();
      }
    };
    return {
      page: 1, // 当前页数
      limit: 5, // 每页显示的数量
      total: 0, // 总记录数
      list: [], // 品牌列表
      dialogFormVisible: false, // 新增或修改品牌对话框是否显示
      tmForm: {    // 新增或修改品牌表单数据
        tmName: "",
        logoUrl: "",
      },
      rules: {   // 新增或修改品牌表单校验规则
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { validator: validateTmName, trigger: "change" },
        ],
        logoUrl: [{ required: true, message: "请选择品牌的图片" }],
      },
    };
  },
  // 页面挂载加载完成后，获取品牌列表
  mounted() {
    this.getPageList();
  },
  methods: {
    // 获取品牌列表
    async getPageList(pager = 1) {
      this.page = pager;
      const { page, limit } = this;
      const res = await this.$API.trademark.reqTradeMarkList(page, limit);
      if (res.code === 200) {
        this.list = res.data.records;
        this.total = res.data.total;
      }
    },

    // 切换每页显示数量分页
    handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },


    // 点击按钮添加事件
    showDialog() {
      this.dialogFormVisible = true;
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },

    // 上传图片成功回调
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = URL.createObjectURL(file.raw);
    },
    // 上传图片之前的钩子函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片格式不正确");
        return false;
      }

      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB");
        return false;
      }

      return true;
    },


    // 修改品牌对话框
    updateTradeMark(row) {
      this.dialogFormVisible = true;
      this.tmForm = { ...row };
    },

    // 添加按钮（添加品牌|修改品牌）
    addOrUpdateTradeMark() {
        // 当全部验证字段通过，再去书写业务逻辑
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const { tmName, logoUrl, id } = this.tmForm;
          try {
            const res = await this.$API.trademark.reqAddOrUpdateTradeMark({
              tmName,
              logoUrl,
              id,
            });
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.dialogFormVisible = false;
              this.getPageList(id ? this.page : 1);
            } else {
              this.$message.error(res.msg);
            }
          } catch (error) {
            this.$message.error("操作失败，请重试");
          }
        } else {
          console.log("error submit!!");
        }
      });
    },

    // 删除品牌
    deleteTradeMark(row) {
      this.$confirm(`你确定删除${row.tmName}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await this.$API.trademark.reqDeleteTradeMark(row.id);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getPageList(this.list.length > 1 ? this.page : this.page - 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
  
  <style scoped>
  .el-dialog{
      --el-dialog-padding-primary: 0px;
  }

.title {
  display: flex;
  align-items: center;
  width:100%-10px;
  height: 40px;
  font-size: 24px;
  /* padding:10px 0px 10px 10px; */
}

h1 {
  margin: 10px 0px;
  font-size: 24px;
  color: #0a279b;
  font-weight: bold;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-upload__tip {
  color: #666;
  font-size: 12px;
  line-height: 1.5;
  text-align: center;
  margin-top: 10px;
}
</style>
  
  
  
  